package chapter5;

import java.security.*;

import javax.crypto.Cipher;

import chapter1.InstallBouncyCastle;
import org.bouncycastle.asn1.*;
import org.bouncycastle.asn1.util.ASN1Dump;
import sun.security.util.ObjectIdentifier;

/**
 * Basic class for exploring a PKCS #1 V1.5 Signature.
 */
public class PKCS1SigEncodingExample extends InstallBouncyCastle {
    public static void main(String[] args) throws Exception {

        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC");
        keyGen.initialize(1024, new SecureRandom());
        KeyPair keyPair = keyGen.generateKeyPair();
        /**
         *
         * 签名中采用如下步骤
         * 1)计算明文hash值hashdata
         * 2)根据ASN.1规则编码hash算法特征串+hashdata，得到签名明文数据C
         * 3)采用RSA私钥加密C得到digest签名数据
         */
        Signature signature = Signature.getInstance("SHA256withRSA", "BC");

        // generate a signature
        signature.initSign(keyPair.getPrivate());
        byte[] message = new byte[]{(byte) 'a', (byte) 'b', (byte) 'c'};
        signature.update(message);
        byte[] sigBytes = signature.sign();

        /**
         *  * 验证过程如下
         *  * 1)采用公钥解密digest,得到C
         *  * 2)根据C，ASN.1解码得到hash算法特征串，获知采用什么hash算法，hashdata是什么
         *  * 3)根据hash算法计算明文的hashdata1，与hashdata比较是否一致
         *  * 4)根据比较结果验证签名的有效性
         */
        // open the signature
        Cipher cipher = Cipher.getInstance("RSA/None/PKCS1Padding", "BC");
        cipher.init(Cipher.DECRYPT_MODE, keyPair.getPublic());
        byte[] decSig = cipher.doFinal(sigBytes);

        // parse the signature
        ASN1InputStream aIn = new ASN1InputStream(decSig);
        ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
        System.out.println("decSig ASN.1 size: " + seq.size());
        System.out.println(ASN1Dump.dumpAsString(seq));

        // grab a digest of the correct type
        MessageDigest hash = MessageDigest.getInstance("SHA-256", "BC");
        hash.update(message);
        byte[] digest = hash.digest();

        DLSequence oid = (DLSequence) seq.getObjectAt(0);
        System.out.println("SHA256算法的oid值：" +oid.getObjectAt(0).toString());
        ASN1OctetString sigHash = (ASN1OctetString) seq.getObjectAt(1);
        if (MessageDigest.isEqual(digest, sigHash.getOctets())) {
            System.out.println("hash verification succeeded");
        } else {
            System.out.println("hash verification failed");
        }
    }
}